#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPixmap>
#include <QPalette>

//文件系统
#include <QDir>
#include <QFile>
#include <QFileInfo>

#include <QMessageBox>
#include <time.h>
#include <QSlider>

//动画
#include <QPropertyAnimation>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /*QMainWindow相关设置*/
    setWindowTitle("超酷的音乐播放器");
    //固定窗口大小
    this->setFixedSize(1020, 720);
    //设置背景
    setBackGround(":/image/background_1.jpg");


    //初始化按钮
    initButtons();

    /*初始化播放器相关设置*/
    initMediaPlayer();

    //加载音乐
    QString musicPath = "E:\\QtDemo\\QtProject002_MusicPlayer\\test.mp3";
    m_player->setMedia(QUrl::fromLocalFile(musicPath));

    //加载指定目录
    m_musicDir = "E:\\QtDemo\\QtProject002_MusicPlayer\\";
    loadLocalMusicDir(m_musicDir);

    //随机数种子
    srand(time(NULL));

    ui->volumSlider->setRange(0, 100);
    ui->volumSlider->setValue(50);

    //绑定音量设置slider
    connect(ui->volumSlider, &QSlider::valueChanged, m_player, &QMediaPlayer::setVolume);
}

MainWindow::~MainWindow()
{
    delete ui;
}


//设置按钮样式
void MainWindow::setButtonStyle(QPushButton* btn, const QString& filename)
{
    //设置按钮的大小
//    btn->setFixedSize(150,150);
    //设置按钮图标
    btn->setIcon(QIcon(filename));
    //设置图标大小
    btn->setIconSize(QSize(ui->prevBtn->width(), ui->prevBtn->height()));
    //设置按钮背景色为透明
    btn->setStyleSheet("background-color:transparent");
}

void MainWindow::initButtons()
{
    setButtonStyle(ui->prevBtn, ":/Icon/prev.png");
    setButtonStyle(ui->nextBtn, ":/Icon/next.png");
    setButtonStyle(ui->playBtn, ":/Icon/play.png");
    setButtonStyle(ui->playModeBtn, ":/Icon/order.png");
    setButtonStyle(ui->playListBtn, ":/Icon/playlist.png");

    //设置音乐列表样式
    ui->musicList->setStyleSheet("QListWidget{"
                            "border:none;"
                            "border-radius:20px;"
                            "background-color:rgba(255,255,255,0.7);}");

    //初始化隐藏音乐列表
    ui->musicList->hide();

    connect(ui->playBtn, &QPushButton::clicked, this, &MainWindow::handlePlaySlot);
    connect(ui->playModeBtn, &QPushButton::clicked, this, &MainWindow::handlePlayModeSlot);
    connect(ui->nextBtn, &QPushButton::clicked, this, &MainWindow::handleNextSlot);
    connect(ui->prevBtn, &QPushButton::clicked, this, &MainWindow::handlePrevSlot);
    connect(ui->playListBtn, &QPushButton::clicked, this, &MainWindow::handlePlayListSlot);
}

//初始化音乐播放器
void MainWindow::initMediaPlayer()
{
    //创建音乐播放器
    m_player = new QMediaPlayer(this);
    //处理音乐位置变化
    connect(m_player, &QMediaPlayer::positionChanged, this, &MainWindow::handlePositionChangedSlot);
    connect(m_player, &QMediaPlayer::durationChanged, this, &MainWindow::handleDurationSlot);
    //当播放器出现错误error时信号被触发
    connect(m_player, QOverload<QMediaPlayer::Error>::of(&QMediaPlayer::error),this,
          [=](QMediaPlayer::Error error){
                //弹窗提示
                QMessageBox::warning(this, "播放器", "播放器失败");
                qDebug() << "error: " << error;
          });
}

//设置背景
void MainWindow::setBackGround(const QString& filename)
{
    //创建照片
    QPixmap pixmap(filename);

    // 获取当前窗口大小
    QSize windowSize = this->size();

    //将照片进行缩放
    QPixmap scalePixmap = pixmap.scaled(windowSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

    //创建QPalette对象并设置背景照片  --调色板
    QPalette palette =  this->palette();
    palette.setBrush(QPalette::Background, QBrush(scalePixmap));

    //将调色板应用到窗口上
    this->setPalette(palette);
}

void MainWindow::handlePlaySlot()
{
    if(m_player->state() == QMediaPlayer::PlayingState)
    {
        m_player->pause();
        ui->playBtn->setIcon(QIcon(":/Icon/play.png"));
    } else{
        m_player->play();
        ui->playBtn->setIcon(QIcon(":/Icon/stop.png"));
    }
}

//处理上一首
void MainWindow::handlePrevSlot()
{
    int currentRow = ui->musicList->currentRow();

    int prevRow = 0;
    if(m_curPlayMode == ORDER_MODE)
    {
        prevRow = currentRow - 1;
        if(prevRow < 0) {
            prevRow = ui->musicList->count() - 1;
        }
    } else if(m_curPlayMode == CIRCLE_MODE)
    {
        prevRow = currentRow;
    } else if(m_curPlayMode == RANDOM_MODE)
    {
        int cnt = 0;
        do {
            prevRow = rand() % ui->musicList->count();
            cnt++;
        }while((currentRow == prevRow) && (cnt < 3));
    }

    //设置音乐列表高亮
    ui->musicList->setCurrentRow(prevRow);

    //播放音乐
    startPlayMusic();
}


//处理下一首
void MainWindow::handleNextSlot()
{
    int currentRow = ui->musicList->currentRow();

    int nextRow = 0;
    if(m_curPlayMode == ORDER_MODE)
    {
        nextRow = (currentRow + 1) % ui->musicList->count();
    } else if(m_curPlayMode == CIRCLE_MODE)
    {
        nextRow = currentRow;
    } else if(m_curPlayMode == RANDOM_MODE)
    {
        int cnt = 0;
        do {
            nextRow = rand() % ui->musicList->count();
            cnt++;
        }while((currentRow == nextRow) && (cnt < 3));
    }

    //音乐列表高亮
    ui->musicList->setCurrentRow(nextRow);

    //播放音乐
    startPlayMusic();
}

void MainWindow::handlePlayListSlot()
{
    if(!m_isShowFlag)
    {
        ui->musicList->show();
        //动画方式：渐入效果展示
        showAnimation(ui->musicList);

        m_isShowFlag = true;
    } else {
        //动画方式：渐出效果展示
        hideAnimation(ui->musicList);

        ui->musicList->hide();
        m_isShowFlag = false;
    }
}

//加载指定文件夹
void MainWindow::loadLocalMusicDir(const QString& filePath)
{
    QDir dir(filePath);
    if(dir.exists() == false)
    {
        QMessageBox::warning(this, "文件夹", "文件夹打开失败");
        return;
    }

    QFileInfoList fileList = dir.entryInfoList(QDir::Files);
    for(auto element: fileList) {
        if(element.suffix() == "mp3")
        {
            ui->musicList->addItem(element.baseName());
        }
    }

    //默认第一行高亮
    ui->musicList->setCurrentRow(0);
}

//处理音乐模式slot
void MainWindow::handlePlayModeSlot()
{
    if(m_curPlayMode == ORDER_MODE)
    {
        m_curPlayMode = RANDOM_MODE;
        ui->playModeBtn->setIcon(QIcon(":/Icon/random.png"));
    } else if(m_curPlayMode == RANDOM_MODE)
    {
        m_curPlayMode = CIRCLE_MODE;
        ui->playModeBtn->setIcon(QIcon(":/Icon/circle.png"));
    } else if(m_curPlayMode == CIRCLE_MODE)
    {
        m_curPlayMode = ORDER_MODE;
        ui->playModeBtn->setIcon(QIcon(":/Icon/order.png"));
    }
}

//处理音乐位置变化
void MainWindow::handlePositionChangedSlot(qint64 position)
{
    //更新进度条和当前时间
    ui->progressBar->setValue(position);

    ui->currentTime->setText(getTimeStr(position));
}

//处理音乐位置变化
void MainWindow::handleDurationSlot(qint64 duration)
{
    //音乐时长转换为进度的里程
    ui->progressBar->setRange(0, duration);

    //将毫秒转换为mm::ss
    ui->totalTime->setText(getTimeStr(duration));
}

//实际播放音乐逻辑
void MainWindow::startPlayMusic()
{
    QString musicName = ui->musicList->currentItem()->text();

    //音乐的绝对路径
    QString musicAbsPath = m_musicDir + musicName + ".mp3";

    //加载音乐
    m_player->setMedia(QUrl::fromLocalFile(musicAbsPath));

    handlePlaySlot();
}

//通过时间戳获取mm::ss字符串
QString MainWindow::getTimeStr(qint64 timestamp)
{
    qint64 timeInSecond = timestamp / 1000;
    qint64 minutes = timeInSecond / 60;
    qint64 seconds = timeInSecond % 60;
    QString timeStr = QString("%1:%2")
                      .arg(minutes, 2, 10, QChar('0'))
                      .arg(seconds, 2, 10, QChar('0'));
    return timeStr;
}

//显示动画
void MainWindow::showAnimation(QWidget* window)
{
    QPropertyAnimation animation(window, "pos");
    //动画持续时间
    animation.setDuration(100);

    //设置起始坐标和结束坐标
    animation.setStartValue(QPoint(this->width(), 0));
    animation.setEndValue(QPoint(this->width() - ui->musicList->width(), 0));
    animation.start();

    QEventLoop loop;
    //信号槽绑定: 等待动画结束
    connect(&animation, &QPropertyAnimation::finished, &loop, &QEventLoop::quit);
    loop.exec();
}

//隐藏动画
void MainWindow::hideAnimation(QWidget* window)
{
    QPropertyAnimation animation(window, "pos");
    //动画持续时间
    animation.setDuration(100);

    //设置起始坐标和结束坐标
    animation.setStartValue(QPoint(this->width() - ui->musicList->width(), 0));
    animation.setEndValue(QPoint(this->width(), 0));
    animation.start();

    QEventLoop loop;
    //信号槽绑定: 等待动画结束
    connect(&animation, &QPropertyAnimation::finished, &loop, &QEventLoop::quit);
    loop.exec();
}
